package com.exam.api.component;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.extra.servlet.JakartaServletUtil;
import com.exam.api.component.dto.WebLog;
import com.exam.api.component.dto.WebLogError;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * @author iaa
 * @Description
 * @Date 2022/6/24 9:20
 */
@Aspect
@Component
public class WebLogAspect {
    private static final Logger log = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("execution(* com.freshcut.api..controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes!=null?attributes.getRequest():null;
        //记录请求信息
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        webLog.setDescription(getOperator(method));

        long endTime = System.currentTimeMillis();
//        String ipAddress = request.getRemoteHost().toString();
//        InetAddress address = InetAddress.getByName(ipAddress);
//        String ip = address.getHostAddress();
        webLog.setIp(JakartaServletUtil.getClientIP(request, ""));
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
//        webLog.setResult(JSONUtil.parse(result));
        webLog.setSpendTime((int) (endTime - startTime));
        webLog.setStartTime(startTime);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        webLog.setClassMethod(signature.getDeclaringTypeName() + "." + signature.getName());

        String authorization = request.getHeader("Authorization");
        Optional<String> tokenOptional = Optional.ofNullable(authorization)
                .map(item -> item.replace("Bearer ", ""));
        if (tokenOptional.isPresent()) {
            Object userId = StpUtil.getLoginIdByToken(tokenOptional.get());
            webLog.setUsername(Convert.toStr(userId, ""));
            webLog.setResult(authorization);
        }
        log.info("{}", webLog);
        return result;
    }

    @AfterThrowing(pointcut = "webLog()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes!=null?attributes.getRequest():null;
        WebLogError error = new WebLogError();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        String authorization = request.getHeader("Authorization");
        error.setUsername(authorization);
        error.setDescription(getOperator(method));
        error.setIp(request!=null?request.getRemoteAddr():"");
        error.setUrl(request!=null?request.getRequestURL().toString():"");
        error.setMethod(request!=null?request.getMethod():"");
        error.setClassMethod(String.format("%s.%s", signature.getDeclaringTypeName(), signature.getName()));
        error.setParameter(getParameter(method, joinPoint.getArgs()));

        error.setException(e.getMessage());
        log.error("Error Request Info : {}", error);
    }


    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (StringUtils.hasLength(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.isEmpty()) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }

    private String getOperator(Method method) {
        if (method.isAnnotationPresent(Operation.class)) {
            Operation apiOperation = method.getAnnotation(Operation.class);
            return apiOperation.summary();
        }
        return null;
    }
}
